<template>
  <Form ref="formInline"
        :model="formInline"
        :rules="ruleInline"
        inline>
    <FormItem prop="username">
      <Input type="text"
             v-model="formInline.username"
             placeholder="Username">
      <Icon type="ios-person-outline"
            slot="prepend"></Icon>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password"
             v-model="formInline.password"
             placeholder="Password">
      <Icon type="ios-lock-outline"
            slot="prepend"></Icon>
      </Input>
    </FormItem>
    <FormItem>
      <Button type="primary"
              @click="signin('formInline')">登录</Button>
      <Button style="margin-left:10px;"
              @click="signup('formInline')">注册</Button>
    </FormItem>
  </Form>
</template>
<script>
import server from "@/api/user";
import Cookies from 'js-cookie';
import crypto from 'crypto';

export default {
  data () {
    return {
      formInline: {
        username: "",
        password: ""
      },
      ruleInline: {
        username: [{ required: true, message: "请输入用户名！", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码！", trigger: "blur" },
          {
            type: "string",
            min: 6,
            message: "密码长度不得小于6位！",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    // MD5加密密码
    encrypt () {
      const md5 = crypto.createHash('md5');
      const md5Sum = md5.update(this.formInline.password.trim());
      return md5Sum.digest('hex');
    },
    signin (name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          const password = this.encrypt();
          let res = await server.login({ username: this.formInline.username.trim(), password });
          if (res.code === 0) {
            // 存入token
            Cookies.set('token', res.data);
            this.$Message.success({
              content: "登录成功!",
              onClose: () => {
                this.$router.push({ name: "Home" });
              }
            });
          }
        }
      });
    },
    signup (name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          const password = this.encrypt();
          let res = await server.signup({ username: this.formInline.username.trim(), password });
          if (res.code === 0) {
            this.$Message.success({
              content: "注册成功!请登录",
            });
          }
        }
      });
    },
  }
};
</script>
